var downFile = require('./tools/downFile.js');
var path = require('path');
var axios = require('axios');
const cheerio = require('cheerio');
const taskCenter = require('./tools/task.js');

// downFile('http://153na.com/tupianqu/KSE/', 'video/43044.html');
// axios.get('http://153na.com/tttppp/1104701.html').then(res => {
//   console.log('行号6:', decodeURIComponent(res.data));
// });

downOneList('http://153na.com/tupianqu/KSE/list103.html');

function downOneList(url) {
  taskCenter.add(() => {
    return axios.get(url).then(res => {
      let $ = cheerio.load(res.data);
      let { dir, root, base, name, ext } = path.parse(url);
      $('#colList ul li a').each((idx, ele) => {
        taskCenter.add(
          downOneGropImgs.bind(null, 'http://153na.com' + $(ele).attr('href'))
        );
      });
    });
  });
}
function downOneGropImgs(url) {
  let { dir, root, base, name, ext } = path.parse(url);
  return axios.get(url).then(res => {
    let $ = cheerio.load(res.data);
    $('.main-content img').each((idx, ele) => {
      taskCenter.add(
        downOneImg.bind(null, $(ele).attr('src'), { groupDir: name, name: idx })
      );
    });
  });
}

function downOneImg(url, { groupDir, name }) {
  let { dir, root, base, ext } = path.parse(url);
  return downFile(url, `imgs/${groupDir}/${name}${ext}`).then(res => {
    console.log('下载成功:', url);
  });
}
